<template>
	<view>
		<cu-custom bgColor="bg-gradual-orange" :isBack="true">
			<block slot="content">会员商品</block>
		</cu-custom>

		<view class="goods-details">
			<view class="page-bg-gray"></view>

			<!-- 商品图片部分 -->
			<view class="image-container">
				<image class="product-image" mode="widthFix" :src="goodsInfo.thumb" />
			</view>

			<!-- 商品详情内容 -->
			<view class="goods-details-content">
				<!-- 商品标题及价格 -->
				<view class="goods-title">
					<view class="goods-item-price-box">
						<view class="price-number-box">
							<view class="price-number">
								<text>￥</text>
								<text class="yuan">{{goodsInfo.money}}</text>
							</view>
						</view>
						<view class="original-price gray">
							<text class="line-through">￥{{goodsInfo.price}}</text>
						</view>
					</view>

					<!-- 商品名称 -->
					<view class="goods-name">
						<view class="box">
							{{goodsInfo.name}}
						</view>
					</view>

					<!-- 销售信息 -->
					<view class="sale-info-box">
						<view class="sale-info">
							<text>月销：{{goodsInfo.stock}}</text>
						</view>
					</view>
				</view>

				<!-- 其他内容区域 -->
				<view class="goods-content-box">
					<view class="content-title">商品介绍</view>
					<view class="content-text" v-for="image in goodsInfo.images">
						<!-- {{goodsInfo.details}} -->
						<image :src="image" mode="widthFix"></image>

					</view>

				</view>
			</view>

			<!-- 优化后的 padding-sm 区域 -->
			<view class="padding-sm">
				<!-- 支付方式选项 -->
				<view class="pay-options">
					<radio-group @change="radioChange">
						<label v-for="payItem in items" :key="payItem.value" class="uni-list-cell uni-list-cell-pd">
							<view class="uni-list-cell-item" style="margin-top:10px">
								<radio :value="payItem.value" :checked="payItem.value === form.pay_type" />
								<text style="padding-left:10rpx;">{{ payItem.name }}</text>
							</view>
						</label>
					</radio-group>
				</view>
			</view>

			<view class="add-form">
				<div v-for="field in formFields" :key="field.name" class="uni-form-item">
					<label class="title">{{ field.label }}</label>
					<input v-if="!field.isArea" class="uni-input" v-model="form[field.name]"
						:placeholder="field.placeholder" :readonly="false" :disabled="false" />
					<yhdslplace v-else @change="change">
						<div class="place" :style="{ color: place ? 'black' : 'grey' }">
							{{ place || '所在地区' }}
						</div>
					</yhdslplace>
				</div>
			</view>
			<button></button>

			<!-- 底部导航栏 -->
			<view class="navigation">
				<!-- <view class="btn buy u-line-1" @click="openVip()">立即购买</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	var wx = require('jweixin-module');
	// #endif

	// #ifdef APP
	import wx from 'weixin-js-sdk';
	// #endif

	const isWechat = () => {
		return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
	};

	import yhdslplace from "@/components/yhdsl-place/yhdsl-place.vue";
	import shop from "@/api/shop";
	import banlance from "@/api/banlance";
	import {
		mapActions,
		mapState
	} from "vuex";

	export default {
		components: {
			yhdslplace
		},
		data() {
			return {
				place: "",
				form: {
					pname: '',
					goods_id: 0,
					amount: 0,
					name: "",
					phone: "",
					region: ["北京市", "北京市", "东城区"],
					detail: "",
					pay_type: '2', // 确保这是字符串
				},
				id: 1,
				skuIsShow: false,
				goodsInfo: {},
				formFields: [{
						name: "name",
						label: "收货人",
						placeholder: "请输入收货人"
					},
					{
						name: "phone",
						label: "手机号码",
						placeholder: "请输入手机号码"
					},
					{
						name: "region",
						label: "所在地区",
						isArea: true
					},
					{
						name: "detail",
						label: "详细地址",
						placeholder: "如道路 门牌号 小区等"
					},
				],
				items: [
					// {
					// 	name: "微信支付",
					// 	value: '1' // 确保这是字符串
					// },
					{
						name: "余额支付",
						value: '2' // 确保这是字符串
					}, {
						name: "银联支付",
						value: '3' // 确保这是字符串
					},
				],
				// 订单id参数
				orderNo: ""
			};
		},
		computed: {
			...mapState(["userInfo"]),
		},
		async onLoad(options) {
			this.id = options.id || 1;
			this.findGoodsInfo();

			// this.getWechatCode()

		},
		methods: {
			toGoods() {
				uni.redirectTo({
					url: '/pages/goods/list'
				})
			},
			async hemafu() {
				// 常量定义
				const NOTIFY_URL = "https://app.yycjkb.cn/api/shande/notifyUrl";
				const RETURN_URL = NOTIFY_URL; // 相同值直接复用

				// 订单 JSON 构建
				let orderjson = {
					version: "10",
					mer_no: "663504000015228",
					mer_order_no: this.getOrderId(),
					create_time: Date.now(),
					expire_time: Date.now() + 1000 * 60 * 5, // 5分钟后过期
					order_amt: this.goodsInfo?.money || 0, // 防止 this.goodsInfo.money 为 undefined
					notify_url: NOTIFY_URL,
					return_url: RETURN_URL,
					create_ip: "", // IP 可以通过后端生成更可靠
					goods_name: this.goodsInfo?.name || "购买商品", // 默认商品名
					store_id: "100001",
					product_code: "01020002",
					clear_cycle: "0",
					pay_extra: {
						wx_app_id: "wx06785591c04f8c56",
						gh_ori_id: "gh_de2d5c2a81ff",
						path_url: "pages/zf/index?",
						miniProgramType: "0"
					},
					jump_scheme: "hemacash://hmpay", // 支付宝跳转
					sign_type: "RSA",
					accsplit_info: "N",
					sign: "", // 签名稍后生成
					meta_option: [{
							sc: "hemacash://hmpay",
							s: "Android",
							id: "cn.zishantang.mall",
							n: "杉德支付"
						},
						{
							sc: "hemacash://hmpay",
							s: "IOS",
							id: "cn.zishantang.mall",
							n: ""
						}
					]
				};

				// 打印 JSON 字符串
				console.log(JSON.stringify(orderjson));

				// 调用 SDK
				try {
					const response = await shop.H5Sdk({
						version: "10",
						mer_no: "663504000015228",
						mer_order_no: this.getOrderId(),
						create_time: Date.now(),
						expire_time: Date.now() + 1000 * 60 * 5, // 5分钟后过期
						order_amt: this.goodsInfo?.money || 0, // 防止 this.goodsInfo.money 为 undefined
						notify_url: "123",
						return_url: "http://192.168.13.126:8081/test/return",
						create_ip: "", // IP 可以通过后端生成更可靠
						goods_name: this.goodsInfo?.name || "购买", // 默认商品名
						store_id: "100001",
						product_code: "01000001",
						clear_cycle: "0",
						pay_extra: "{}",
						meta_option: [{
								"s": "Android",
								"n": "",
								"id": "",
								"sc": ""
							},
							{
								"s": "IOS",
								"n": "",
								"id": "",
								"sc": ""
							}
						],
						accsplit_info: "N",
						jump_scheme: "sandcash://scpay",
						sign_type: "RSA",
						sign: ""
					});

					if (response.code === 1) {
						const url = `https://cash.sandgate.cn/h5/?${response.data}#/hippoPublic`;
						console.log(url);
						// window.location = url; // 启用跳转时取消注释
					} else {
						console.error("Error:", response);
					}
				} catch (error) {
					console.error("Exception occurred:", error);
				}


			},

			getOrderId() {
				// 假设 this.auth.id 是用户 ID
				const authId = this.userInfo.id; // 示例用户 ID，实际从逻辑中获取

				// 获取 authId 的后 6 位，不足用 0 填充
				const idPart = String(authId).slice(-6).padStart(6, '0');

				// 获取当前日期，格式化为 ymdH（年-月-日-小时）
				const now = new Date();
				const datePart = now.getFullYear().toString().slice(-2) + // 年的后两位
					String(now.getMonth() + 1).padStart(2, '0') + // 月（0-11 需 +1）
					String(now.getDate()).padStart(2, '0') + // 日
					String(now.getHours()).padStart(2, '0'); // 小时

				// 拼接订单号
				const orderSn = `FLL${idPart}${datePart}`;

				console.log(orderSn); // 输出：FLL00123423120610

				return orderSn;

			},
			showGoodsSku() {
				this.skuIsShow = true;
			},
			closeSku() {
				this.skuIsShow = false;
			},
			async findGoodsInfo() {
				await banlance.getProductDetail({
					id: this.id
				}).then(res => {
					if (res.code == 1) {
						this.goodsInfo = res.data;
						console.log(res);
					} else {
						console.log(res);
					}
				});
			},
			getWechatCode() {
				if (isWechat) {
					let appid = "wx06785591c04f8c56"; //微信APPid
					let code = this.getUrlCode().code; //是否存在code
					let local = window.location.href;
					if (code == null || code === "") {
						//不存在就打开上面的地址进行授权
						window.location.href =
							"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
							appid +
							"&redirect_uri=" +
							encodeURIComponent(local) +
							"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
					} else {
						this.code = code;
						// alert(this.code)
						this.getCode()
					}
				}
			},
			async getCode() {
				shop.getOpenid({
					code: this.code
				}).then(res => {
					if (res.code == 1) {
						this.disabled = true;
						this.loading = false;
						// this.toast(res.msg);
						// window.location.href = res.data
						// this.status = res.msg;
						console.log('添加成功');
						// this.goBack();
					} else {
						this.loading = false
						// this.toast(res.msg);
					}
				})
			},
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				console.log(url)
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				console.log(theRequest);
				return theRequest;
			},
			changeSwiper() {

			},
			change(val) {
				this.form.region = val.data;
				this.place = val.data.join(",");
			},
			radioChange(evt) {
				this.form.pay_type = evt.target.value;
			},
			openVip() {
				uni.showModal({
					title:'暂停注册'
				})
				return;

				if (!this.form.name || !this.form.phone || !this.form.detail) {
					return uni.showToast({
						title: "请填写完整信息",
						icon: "none"
					});
				}
				this.form.amount = this.goodsInfo.money;
				// this.form.goods_id = this.id;
				this.form.pname = this.goodsInfo.name;
				console.log(this.form.pname)
				shop.userlevel(this.form).then((res) => {
					console.log(res);
					if (res.code === 0) {
						return uni.showToast({
							title: res.msg
						});
					}
					if (this.form.pay_type == 2) {
						uni.showModal({
							title: "恭喜您升级成功"
						});
						// 2s后跳转首页
						setTimeout(() => uni.switchTab({
							url: "/pages/my/index"
						}), 2000);
					} else if (this.form.pay_type == 3) {
						console.log(res.data);
						if (res.code === 1) {
							window.location.href = res.data.url;
						}
					} else {
						// this.handlePayment(res.data.pay);

						// 微信支付参数
						const payParams = res.data.pay;
						console.log("payParams:" + payParams);
						// 调用微信支付
						this.initiateWechatPayment(payParams);
						// // 调用微信支付
						// uni.requestPayment({
						// 	provider: 'wxpay',
						// 	orderInfo: {
						// 		appId: payParams.appId,
						// 		timeStamp: payParams.timeStamp,
						// 		nonceStr: payParams.nonceStr,
						// 		package: payParams.package,
						// 		signType: payParams.signType,
						// 		paySign: payParams.paySign
						// 	},
						// 	success: (paymentRes) => {
						// 		// 支付成功后的回调
						// 		console.log('支付成功', paymentRes);
						// 		uni.showModal({
						// 			title: "恭喜您升级成功"
						// 		});
						// 		// 2s后跳转首页
						// 		setTimeout(() => uni.switchTab({
						// 			url: "/pages/my/index"
						// 		}), 2000);
						// 	},
						// 	fail: (paymentErr) => {
						// 		// 支付失败后的回调
						// 		console.log('支付失败', paymentErr);
						// 		uni.showToast({
						// 			title: '支付失败，请重试',
						// 			icon: 'none'
						// 		});
						// 	}
						// });
					}
				});

			},
			initiateWechatPayment(payParams) {
				wx.config({
					appId: payParams.appId,
					timestamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					signature: payParams.paySign,
					jsApiList: ["chooseWXPay"]
				});

				wx.ready(() => {
					wx.chooseWXPay({
						timestamp: payParams.timeStamp,
						nonceStr: payParams.nonceStr,
						package: payParams.package,
						signType: payParams.signType,
						paySign: payParams.paySign,
						success: (res) => {
							console.log("支付成功", res);
							uni.showModal({
								title: "恭喜您升级成功"
							});
							setTimeout(() => uni.switchTab({
								url: "/pages/my/index"
							}), 2000);
						},
						fail: (err) => {
							console.error("支付失败", err);
							uni.showToast({
								title: "支付失败，请重试",
								icon: "none"
							});
						}
					});
				});
				wx.error((err) => {
					console.error("微信支付 SDK 配置错误", err);
					uni.showToast({
						title: "微信支付初始化失败，请重试",
						icon: "none"
					});
				});
			},

			handlePayment(wxpay) {
				wx.config({
					appId: "wx06785591c04f8c56",
					timestamp: wxpay.timeStamp,
					nonceStr: wxpay.nonceStr,
					signature: wxpay.paySign,
					jsApiList: ["chooseWXPay"],
				});
				wx.ready(() => {
					wx.chooseWXPay({
						timestamp: wxpay.timeStamp,
						nonceStr: wxpay.nonceStr,
						package: wxpay.package,
						signType: "MD5",
						paySign: wxpay.paySign,
						success: () => {
							uni.showModal({
								title: "恭喜您升级成功"
							});
							// 2s后跳转首页
							setTimeout(() => uni.switchTab({
								url: "/pages/my/index"
							}), 2000);
							// 2s后跳转优惠券页面
							// setTimeout(() => uni.navigateTo({
							// 	url: "/pages/coupon/index?payMoney=" + this.goodsInfo.money
							// }), 2000);
						},
						fail: () => uni.showToast({
							title: "支付失败",
							icon: "none"
						}),
					});
				});
			},
		},

	};
</script>

<style lang="scss" scoped>
	.add-form {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
		padding: 20rpx;
		background-color: #f9f9f9;
		border-radius: 20rpx;
		margin: 20rpx;
		margin-bottom: 150px;

		.uni-form-item {
			display: flex;
			flex-direction: column;
			gap: 10rpx;

			.title {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
			}

			.uni-input {
				font-size: 30rpx;
				border: 1px solid #e0e0e0;
				border-radius: 10rpx;
				background-color: white;
				width: 100%;
				height: 80rpx;
				padding: 10rpx;
				box-sizing: border-box;
			}

			.place {
				padding: 15rpx;
				font-size: 30rpx;
				border: 1px solid #e0e0e0;
				border-radius: 10rpx;
				background-color: white;
				text-align: center;
			}
		}

		button {
			width: 100%;
			margin-top: 20rpx;
			padding: 15rpx;
			background-color: #ff9900;
			color: white;
			border: none;
			border-radius: 10rpx;
			font-size: 32rpx;
			font-weight: 600;
			text-align: center;

			&:active {
				background-color: #e68a00;
			}
		}
	}

	.goods-details {
		background-color: #fff;
	}

	/* 图片样式美化 */
	.image-container {
		padding: 5px;
		display: flex;
		justify-content: center;
	}

	.product-image {
		width: 95%;
		border-radius: 15px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		object-fit: cover;
	}

	/* 商品标题及价格部分 */
	.goods-title {
		background: #fff;
		padding: 20px;
		margin-bottom: 15px;
		border-radius: 12px;
	}

	.goods-item-price-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 15px;
	}

	.price-number-box {
		display: flex;
		align-items: baseline;
		font-weight: bold;

		.yuan {
			font-size: 60rpx;
			color: #ff201f;
		}

		.original-price {
			font-size: 13px;
			line-height: 13px;
			padding: 5px 0;
			box-sizing: border-box;
			color: #999;

			.line-through {
				text-decoration: line-through;
			}
		}
	}

	/* 商品名称样式 */
	.goods-name .box {
		font-size: 18px;
		font-weight: 500;
		margin-top: 12px;
		line-height: 1.6;
	}

	/* 销售信息部分 */
	.sale-info-box {
		font-size: 14px;
		color: #666;
		padding: 0 30rpx;
		margin-top: 10px;
		line-height: 1.6;
	}

	/* 内容区样式 */
	.goods-content-box {
		// height: 100px;
		// background-color: #fafafa;
		// border-radius: 10px;
		// padding: 20px;
		margin: 15px 15px 0 15px;

		.content-title {
			font-size: 20px;
			font-weight: bold;
			margin-bottom: 12px;
		}

		.content-text {
			font-size: 16px;
			line-height: 1.8;
			color: #333;
			display: flex;
			justify-content: center;

			image {
				width: 100%;
				height: auto;
			}
		}

	}

	/* 支付选项样式 */
	.pay-options {
		display: flex;
		justify-content: space-between;
		/* 使两个选项在行中分开 */
		padding: 10px;
		/* 适当的内边距 */
	}

	/* 底部导航按钮 */
	.navigation {
		// position: fixed;
		// bottom: 0;
		width: 100%;
		background-color: #fff;
		display: flex;
		justify-content: center;
		padding: 10px 0;

		.btn {
			width: 90%;
			padding: 14px;
			text-align: center;
			background-color: #ff4d4f;
			color: #fff;
			border-radius: 8px;
			font-weight: bold;
			font-size: 18px;
		}
	}
</style>